public class Test {
    public static void main(String[] args) throws Exception {
        ChatRoom room = new ChatRoom();

        User alice = new User("Alice", room);
        User bob = new User("Bob", room);
        User carol = new User("Carol", room);

        room.addUser(alice);
        room.addUser(bob);
        room.addUser(carol);

        alice.send("大家好！"); // 广播
    }
}
// 中介者模式（Mediator） = “把网状通信变成星型通信”
// 对象之间不直接说话，全部发给一个中介对象（仲裁者/消息总线），由中介统一分发，彻底解耦
/* ---------- 抽象同事 ---------- */
abstract class Colleague {
    protected Mediator mediator;

    Colleague(Mediator m) {
        this.mediator = m;
    }

    abstract void send(String msg);

    abstract void receive(String msg);
}

/* ---------- 具体同事 ---------- */
class User extends Colleague {
    private String name;

    User(String name, Mediator m) {
        super(m);
        this.name = name;
    }

    void send(String msg) {
        System.out.println(name + " 发送: " + msg);
        mediator.relay(this, msg);
    }

    void receive(String msg) {
        System.out.println(name + " 收到: " + msg);
    }
}

/* ---------- 中介接口 & 实现 ---------- */
interface Mediator {
    void relay(Colleague from, String msg);
}

class ChatRoom implements Mediator {
    private final java.util.List<Colleague> users = new java.util.ArrayList<>();

    void addUser(Colleague u) {
        users.add(u);
    }

    public void relay(Colleague from, String msg) {
        users.stream()
                .filter(u -> u != from)
                .forEach(u -> u.receive(msg));
    }
}